<?php
class ApiSDK{
	//缓存时间
	public $cache_time  = 600;
	//记录数
	public $count       = 0;
	//总页数
	public $total_page  = 0;
	//接口返回信息
	public $api_reinfo  = '';
	//接口请求参数
	public $params      = array();
	//终端类型
	public $app_type    = 'web';
	//内部版本号
	public $app_version = '1';
	//授权ID
	public $app_auth_id = '';
	//授权签名KEY
	public $appkey      = '';
	
	
	public function _initialize(){
		//从SESSION中获取用户TOKEN
		$this->user_token   = $this->user_token();
		$this->user_token   = $this->user_token ? $this->user_token : '';
		$this->app_type     = $this->app_type ? $this->app_type : 'web';
		$this->app_version  = $this->app_version ? $this->app_version : '1';
		//设置授权ID
		$this->app_auth_id  = 1;
		//设置授权时间
		$this->app_authtime = time();
		//设置授权签名KEY
		$this->appkey       = 'rh54TMWLC9mnyynM';

	}
	//获取用户TOKEN
	public function user_token(){
		return session('user_token');
	}
	/**
	 * 保存用户SESSION
	 * @param  string $user_info 用户信息
	 */
	public function save_session($user_info = ''){
		$time = 24 * 60 * 60;
		session(array('expire' => $time));
		//保存用户信息
		session('user_info', $user_info);
		//保存用户TOKEN
		session('user_token', $user_info['token']);
	}
	/**
	 * 更新用户SESSION信息
	 */
	public function update_session(){
		$data = $this->get('user/get_user_info', $params);
		if($data['status'] == '200'){
			$this->save_session($data['data']);
		}
	}
	/**
	 * 获取用户信息
	 */
	public function get_user_info(){
		$data = $this->get('user/get_user_info', $params);
		if($data['status'] == '200'){
			$this->save_session($data['data']);
			return $data['data'];
		}
		return false;
	}
	/**
	 * 第三方注册
	 * @param  string  $sso_type 第三方类型
	 * @param  string  $open_id  第三方唯一标识
	 * @param  string  $nickname 昵称
	 * @param  integer $sex      性别
	 * @param  string  $head_url 头像URL
	 */
	public function sso_register($sso_type = 'weibo', $open_id = '', $nickname = '', $sex = 0, $head_url = ''){
		$params['sso_type']  = $sso_type;
		$params['open_id']   = $open_id;
		$params['nickname']  = $nickname;
		$params['sex']       = $sex;
		$params['head_url']  = urlencode($head_url);
		$info = $this->post('user/sso_register', $params);
		if($info['status'] == '200'){
			$this->save_session($info['data']);
			return true;
		}else{
			return false;
		}
	}
	/**
	 * 第三方登录
	 * @param  string $sso_type 第三方类型
	 * @param  string $open_id  第三方唯一标识
	 */
	public function sso_login($sso_type = 'weibo', $open_id = ''){
		$params['sso_type'] = $sso_type;
		$params['open_id']  = $open_id;
		$info = $this->post('user/sso_login', $params);
		if($info['status'] == '200'){
			$this->save_session($info['data']);
			return true;
		}else{
			return false;
		}
	}
	/**
	 * 第三方登录
	 * @param  string $sso_type 第三方类型
	 * @param  string $open_id  第三方唯一标识
	 */
	public function sso_bind($sso_type = 'weibo', $open_id = '', $nickname = ''){
		$params['sso_type'] = $sso_type;
		$params['open_id']  = $open_id;
		$params['nickname'] = $nickname;
		$info = $this->post('user/sso_bind', $params);
		if($info['status'] == '200'){
			$this->update_session();
			return true;
		}else{
			return false;
		}
	}
	/**
	 * 取消绑定
	 * @param  string $type 绑定类型
	 */
	public function sso_unbind($sso_type = 'weixin'){
		$params['sso_type'] = $sso_type;
		$info = $this->post('user/sso_unbind', $params);
		if($info['status'] == '200'){
			$this->update_session();
			return true;
		}else{
			return false;
		}
	}
	/**
	 * 图片裁剪
	 * @param  [type] $file_id 文件ID
	 * @param  [type] $x1      [description]
	 * @param  [type] $y1      [description]
	 * @param  [type] $x2      [description]
	 * @param  [type] $y2      [description]
	 * @param  [type] $width   [description]
	 * @param  [type] $height  [description]
	 * @return [type]          [description]
	 */
	public function file_id_img_crop($file_id, $x1, $y1, $x2, $y2, $width, $height){
		$params['file_id'] = $file_id;
		$params['x1']      = $x1 ? $x1 : 0;
		$params['y1']      = $y1 ? $y1 : 0;
		$params['x2']      = $x2;
		$params['y2']      = $y2;
		$params['width']   = $width;
		$params['height']  = $height;
		$data = $this->post('file/img_crop', $params);
		if($data['status'] == 200){
			return $data['data'];
		}else{
			return false;
		}
	}
	/**
	 * 图片裁剪
	 * @param  [type] $file_id 文件ID
	 * @param  [type] $x1      [description]
	 * @param  [type] $y1      [description]
	 * @param  [type] $x2      [description]
	 * @param  [type] $y2      [description]
	 * @param  [type] $width   [description]
	 * @param  [type] $height  [description]
	 * @return [type]          [description]
	 */
	public function user_head_crop($file_id, $x1, $y1, $x2, $y2, $width, $height){
		$params['file_id'] = $file_id;
		$params['x1']      = $x1 ? $x1 : 0;
		$params['y1']      = $y1 ? $y1 : 0;
		$params['x2']      = $x2;
		$params['y2']      = $y2;
		$params['width']   = $width;
		$params['height']  = $height;
		$data = $this->post('user/head_crop', $params);
		if($data['status'] == 200){
			$this->update_session();
			return $data['data'];
		}else{
			return false;
		}
	}
	/**
	 * 频道栏目
	 * @param  integer $parentid   父ID
	 * @param  integer $cache_time 缓存时间
	 */
	public function get_channel_list($parentid = 0, $cache_time = 3600){
		$new_list = array();
		$params['parentid'] = $parentid;
		$data = $this->get('channel/index', $params, $cache_time);
		if($data['status'] == '200'){
			$list = $data['data']['list'];
		}
		foreach ($list as $rs) {
			switch ($rs['module']) {
				case 'Article':
					if(C('URL_ROUTER_ON')){
						$rs['url'] = ($rs['identy'] ? '/' . $rs['identy'] : 'Index/' . $rs['channel_id']);
					}else{
						$rs['url'] = 'Index/index?channel_id=' . $rs['channel_id'];
					}
					break;

				default:
					$rs['url'] = '/';
					break;
			}
			$new_list[] = $rs;
		}
		// var_dump($new_list);exit;
		return $new_list;
	}
	/**
	 * 获取频道栏目名称
	 * @param  string $channel_id 栏目ID
	 */
	public function get_channel_name($channel_id=''){
		if(!$channel_id){
			return '';
		}
		$channel_name = '';
		$list = $this->get_channel_list();
		foreach ($list as $rs) {
			if($rs['channel_id'] == $channel_id){
				$channel_name = $rs['title'];
				break;
			}
		}
		return $channel_name;
	}
	/**
	 * 获取标识栏目ID
	 * @param  [type] $identy 标识
	 */
	public function get_identy_channel_id($identy){
		if(!$identy){
			return '';
		}
		$channel_id = '';
		$list = $this->get_channel_list();
		foreach ($list as $rs) {
			if($rs['identy'] == $identy){
				$channel_id = $rs['channel_id'];
				break;
			}
		}

		return $channel_id ? $channel_id : '';
	}
	/**
	 * 获取标识栏目信息
	 * @param  [type] $identy 标识
	 */
	public function get_identy_channel_info($identy){
		if(!$identy){
			return '';
		}
		$info = '';
		$list = $this->get_channel_list();
		foreach ($list as $rs) {
			if($rs['identy'] == $identy){
				$info = $rs;
				break;
			}
		}

		return $info ? $info : '';
	}
	/**
	 * 获取配置信息
	 * @param  string $name 配置KEY
	 * @param  string $type 配置类型
	 */
	public function config($name = '', $type = 'system', $cache_time = 300){
		$params['type'] = $type;
		$data = $this->get('config/info', $params, $cache_time);
		if($data['status'] == '200'){
			$config = $data['data'];
		}
		if($name && $type){
			$info = $config[$type][$name];
		}elseif($type){
			$info = $config[$type];
		}else{
			$info = $config;
		}
		return $info;
	}
	/**
	 * 获取类别列表
	 * @param  string $module [description]
	 * @return [type]         [description]
	 */
	public function get_category_list($module = '', $cache_time = 3600){
		$list = array();
		$params['module'] = $module;
		$data = $this->get('other/get_category', $params, $cache_time);
		if($data['status'] == '200'){
			$list = $data['data']['list'];
		}
		return $list;
	}
	/**
	 * 获取文章列表
	 * @param  string  $channel_id 栏目ID
	 * @param  integer $page       第几页
	 * @param  integer $pagesize   每页显示数量
	 */
	public function get_article_list($channel_id = '', $page = 1, $pagesize = 10){
		$list = array();
		$params['channel_id'] = $channel_id;
		$params['page']       = $page;
		$params['pagesize']   = $pagesize;
		$data = $this->get('article/index', $params);
		if($data['status'] == '200'){
			$list       = $data['data']['list'];

			$this->count      = $data['data']['page_info']['count'];
			$this->total_page = $data['data']['page_info']['total_page'];
		}
		return $list;
	}
	/**
	 * 获取用户文章列表
	 * @param  integer $page       第几页
	 * @param  integer $pagesize   每页显示数量
	 */
	public function get_user_article_list($page = 1, $pagesize = 10){
		$list = array();
		$params['is_user_self'] = 1;
		$params['page']         = $page;
		$params['pagesize']     = $pagesize;

		$new_params = array_merge($params, $this->params);
		$data = $this->get('article/index', $new_params);
		if($data['status'] == '200'){
			$list       = $data['data']['list'];

			$this->count      = $data['data']['page_info']['count'];
			$this->total_page = $data['data']['page_info']['total_page'];
		}
		return $list;
	}
	/**
	 * 添加文章
	 * @param [type] $title       标题
	 * @param [type] $description 描述
	 * @param [type] $content     内容
	 * @param [type] $cover_id    封面文件ID
	 */
	public function add_article($channel_id, $title, $description, $content, $cover_id = ''){
		$params['channel_id']  = $channel_id;
		$params['title']       = $title;
		$params['description'] = $description;
		$params['content']     = $content;
		$params['cover_id']    = $cover_id;

		$new_params = array_merge($params, $this->params);
		$data = $this->post('article/add', $new_params);
		$this->api_reinfo = $data['info'];
		if($data['status'] == '200'){
			return $data['data'];
		}
		return false;
	}
	/**
	 * 添加文章
	 * @param [type] $article_id  文章ID
	 * @param [type] $title       标题
	 * @param [type] $description 描述
	 * @param [type] $content     内容
	 * @param [type] $cover_id    封面文件ID
	 */
	public function edit_article($article_id, $channel_id, $title, $description, $content, $cover_id = ''){
		$params['article_id']  = $article_id;
		$params['channel_id']  = $channel_id;
		$params['title']       = $title;
		$params['description'] = $description;
		$params['content']     = $content;
		$params['cover_id']    = $cover_id;

		$new_params = array_merge($params, $this->params);
		$data = $this->post('article/edit', $new_params);
		if($data['status'] == '200'){
			return $data['data'];
		}
		return false;
	}
	/**
	 * 删除文章
	 * @param  [type] $article_id 文章ID
	 */
	public function delete_article($article_id){
		$params['article_id']  = $article_id;
		$data = $this->post('article/delete', $params);
		$this->api_reinfo = $data['info'];
		if($data['status'] == '200'){
			return true;
		}
		return false;
	}
	/**
	 * 设置文章上线
	 */
	public function set_article_on($article_id){
		$params['article_id']  = $article_id;
		$data = $this->post('article/set_on', $params);
		$this->api_reinfo = $data['info'];
		if($data['status'] == '200'){
			return true;
		}
		return false;
	}
	/**
	 * 设置文章上线
	 */
	public function set_article_off($article_id){
		$params['article_id']  = $article_id;
		$data = $this->post('article/set_off', $params);
		$this->api_reinfo = $data['info'];
		if($data['status'] == '200'){
			return true;
		}
		return false;
	}
	/**
	 * 热门文章列表
	 * @param  string  $channel_id 栏目ID
	 * @param  integer $page       第几页
	 * @param  integer $pagesize   每页显示数量
	 */
	public function get_article_hot_list($channel_id = '', $page = 1, $pagesize = 10){
		$list = array();
		$params['is_hot']     = 1;
		$params['channel_id'] = $channel_id;
		$params['page']       = $page;
		$params['pagesize']   = $pagesize;
		$data = $this->get('article/index', $params, $this->cache_time);
		if($data['status'] == '200'){
			$list = $data['data']['list'];

			$this->count      = $data['data']['page_info']['count'];
			$this->total_page = $data['data']['page_info']['total_page'];
		}
		return $list;
	}
	/**
	 * 最新文章列表
	 * @param  string  $channel_id 栏目ID
	 * @param  integer $page       第几页
	 * @param  integer $pagesize   每页显示数量
	 */
	public function get_article_new_list($channel_id = '', $page = 1, $pagesize = 10){
		$list = array();
		$params['is_new']     = 1;
		$params['channel_id'] = $channel_id;
		$params['page']       = $page;
		$params['pagesize']   = $pagesize;
		$data = $this->get('article/index', $params, $this->cache_time);
		if($data['status'] == '200'){
			$list       = $data['data']['list'];

			$this->count      = $data['data']['page_info']['count'];
			$this->total_page = $data['data']['page_info']['total_page'];
		}
		return $list;
	}
	
	/**
	 * 获取文章内容
	 * @param  string $id 文章ID
	 */
	public function get_article_detail($article_id='', $is_user_self = 0){
		$info = array();
		$params['article_id']   = $article_id;
		$params['is_user_self'] = $is_user_self ? $is_user_self : 0;
		$data = $this->get('article/detail', $params);
		if($data['status'] == '200'){
			$info = $data['data'];
		}
		return $info;
	}
	/**
	 * 获取阅读金额
	 * @param  [type] $article_id 文章ID
	 */
	public function get_read_article_money($article_id){
		$params['article_id'] = $article_id;
		$data = $this->post('article/get_read_money', $params);
		if($data['status'] == '200'){
			return true;
		}
		return false;
	}
	/**
	 * 获取单篇文章内容
	 * @param  string $module 模块标识
	 */
	public function get_page_detail($module = 'about'){
		$info = array();
		$params['module'] = $module;
		$data = $this->get('page/detail', $params);
		if($data['status'] == '200'){
			$info = $data['data'];
		}
		return $info;
	}
	/**
	 * 获取文章列表
	 * @param  string  $article_id 文章ID
	 * @param  integer $page       第几页
	 * @param  integer $pagesize   每页显示数量
	 */
	public function get_article_comment_list($article_id = '', $page = 1, $pagesize = 10){
		$list = array();
		$params['article_id'] = $article_id;
		$params['page']       = $page;
		$params['pagesize']   = $pagesize;
		$data = $this->get('article/comment_list', $params);
		if($data['status'] == '200'){
			$list = $data['data']['list'];

			$this->count      = $data['data']['page_info']['count'];
			$this->total_page = $data['data']['page_info']['total_page'];
		}
		return $list;
	}
	/**
	 * 获取用户收藏列表
	 * @param  integer $page       第几页
	 * @param  integer $pagesize   每页显示数量
	 */
	public function get_user_fav_list($page = 1, $pagesize = 10){
		$list = array();
		$params['page']       = $page;
		$params['pagesize']   = $pagesize;
		$data = $this->get('article/fav_list', $params);
		if($data['status'] == '200'){
			$list = $data['data']['list'];

			$this->count      = $data['data']['page_info']['count'];
			$this->total_page = $data['data']['page_info']['total_page'];
		}
		return $list;
	}
	/**
	 * 设置文章收藏
	 */
	public function set_article_fav($article_id = ''){
		$params['article_id'] = $article_id;
		$data = $this->post('article/set_fav', $params);
		
		return $data['info'];
	}
	/**
	 * 获取用户账单清单
	 * @param  integer $page     第几页
	 * @param  integer $pagesize 每页显示数量
	 */
	public function get_user_bill_list($page = 1, $pagesize = 10){
		$list = array();
		$params['page']       = $page;
		$params['pagesize']   = $pagesize;
		$data = $this->get('account/bill_list', $params);
		if($data['status'] == '200'){
			$list = $data['data']['list'];

			$this->count      = $data['data']['page_info']['count'];
			$this->total_page = $data['data']['page_info']['total_page'];
		}
		return $list;
	}
	/**
	 * 获取用户积分列表
	 * @param  integer $page       第几页
	 * @param  integer $pagesize   每页显示数量
	 */
	public function get_user_score_list($page = 1, $pagesize = 10){
		$list = array();
		$params['page']     = $page;
		$params['pagesize'] = $pagesize;
		$data = $this->get('user/score_list', $params);
		if($data['status'] == '200'){
			$list = $data['data']['list'];

			$this->count      = $data['data']['page_info']['count'];
			$this->total_page = $data['data']['page_info']['total_page'];
		}
		return $list;
	}
	/**
	 * 获取银行列表
	 */
	public function get_bank_list(){
		$params['module'] = 'bank_name_list';
		$data = $this->get('other/get_category', $params);

		return $data['status'] == '200' ? $data['data']['list'] : array();
	}
	/**
	 * 获取用户银行卡清单
	 */
	public function get_user_bank_card(){
		$data = $this->get('account/my_bank_card');

		return $data['status'] == '200' ? $data['data']['list'] : array();
	}
	/**
	 * 获取用户账户信息
	 */
	public function get_account_info(){
		$data = $this->get('account/account_info');

		return $data['status'] == '200' ? $data['data'] : array();
	}
	/**
	 * 用户提现
	 */
	public function take_out($card_id = '', $money = 100){
		$params['card_id'] = $card_id;
		$params['money']   = $money;
		$data = $this->post('account/take_out', $params);
		if($data['status'] == '200'){
			return true;
		}
		return false;
	}

	/**
	 * 获取微信配置信息
	 */
	public function get_weixin_config(){
		$info = array();
		$data = $this->get('weixin/get_config');
		if($data['status'] == '200'){
			$info = $data['data'];
		}
		return $info;
	}
	/**
	 * 设置微信配置
	 * @param string $token     Token
	 * @param string $appid     App ID
	 * @param string $appsecret App Secret
	 */
	public function set_weixin_config($token = '', $appid = '', $appsecret = ''){
		$params['token']     = $token;
		$params['appid']     = $appid;
		$params['appsecret'] = $appsecret;
		$data = $this->post('weixin/set_config', $params);
		if($data['status'] == '200'){
			return true;
		}
		return false;
	}
	
	//IP获取城市信息
	public function ip2city($ip){
		$params['ip'] = $ip;
		$data = $this->get('other/ip2city', $params, 30 * 60);
		if($data['status'] == '200'){
			$info = $data['data'];
		}
		if(!$info){
			$info['id']   = '52';
			$info['name'] = '北京';
		}
		return $info;
	}
	
	/**
	 * POST接口
	 * @param  string $method [description]
	 * @param  [type] $params [description]
	 * @return [type]         [description]
	 */
	public function post($method = '', $params, $cache_time = 0){
		$data       = '';
		$new_params = array_merge($params, $this->params);
		$key        = 'WEB_API_DATA_' . md5($method . http_build_query($new_params) . $cache_time);
		if($cache_time > 0){
			$data = S($key);
		}
		if(!$data){
			$data = $this->api($method, $new_params, 'POST');
			//缓存数据
			if($cache_time > 0 && $data['status'] == '200'){
				S($key, $data, $cache_time);
			}
		}
		return $data;
	}
	/**
	 * GET接口
	 * @param  string $method [description]
	 * @param  [type] $params [description]
	 * @return [type]         [description]
	 */
	public function get($method = '', $params, $cache_time = 0){
		$data       = '';
		$new_params = array_merge($params, $this->params);
		$key        = 'WEB_API_DATA_' . md5($method . http_build_query($new_params) . $cache_time);
		if($cache_time > 0){
			$data = S($key);
		}
		if(!$data){
			$data = $this->api($method, $new_params, 'GET');
			//缓存数据
			if($cache_time > 0 && $data['status'] == '200'){
				S($key, $data, $cache_time);
			}
		}
		return $data;
	}
	/**
	 * [api description]
	 * @param  [type] $url    [description]
	 * @param  [type] $params [description]
	 * @param  string $method [description]
	 * @return [type]         [description]
	 *
	 * api('tour/detail',$parmas);
	 */
	public function api($url, $params, $method = 'GET'){
		$web_path = defined('DOMAIN_PATH') ? DOMAIN_PATH : '';

		//设置签名
		$this->app_sign = $this->generate_sign($method == 'GET' ? $params : '');
		
		$apiurl = $web_path . '/api.php/' . $url;
		if($method == 'GET'){
			$result_str = $this->http($apiurl . '?' . http_build_query($params));
		}else{
			$result_str = $this->http($apiurl, $params, 'POST');
		}

		$result = array();
		if($result_str != ''){
			$result    = json_decode($result_str, true);
			$login_url = URL('Login/index', '', '/login');
			//登录超时处理
			if($result['status'] == '202'){
				session(null);
				if($this->isAjax()){
					$this->json_error($result['info'], array('url', $login_url), 202);
				}
				redirect($login_url);
			}
			$this->api_reinfo = $result['info'];
		}
		return $result;
	}
	public function http($url, $postfields='', $method='GET', $headers=array()){
		$header = array(
			'APP-AUTH-ID: ' . $this->app_auth_id,
			'APP-SIGN: ' . $this->app_sign,
			'APP-AUTHTIME: ' . $this->app_authtime,
			'APP-TYPE: ' . $this->app_type,//WEB版本
			'APP-VERSION: ' . $this->app_version,//内部版本
			'APP-TOKEN: ' . $this->user_token(),
			'APP-IMEI: ' . session_id(),
		);
		// var_dump($url);exit;
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); 
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
		curl_setopt($ch, CURLOPT_TIMEOUT, 30);
		if($method == 'POST'){
			curl_setopt($ch, CURLOPT_POST, TRUE);
			if($postfields != '')curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
		}
		curl_setopt($ch, CURLOPT_URL, $url);
		$response = curl_exec($ch);
		// var_dump($response);exit;
		curl_close($ch);
		return $response;
	}
	//生成接口签名
	protected function generate_sign($params = ''){
		//设置签名参数
		$params['header_auth_id']      = $this->app_auth_id;
		$params['header_app_token']    = $this->user_token();
		$params['header_app_authtime'] = $this->app_authtime;
		$debug['params'] = $params;

		//将数组按abc顺序排序参数
		ksort($params);
		$debug['sort_params'] = $params;

		//将数组转成URL参数字符串
		$url_params = http_build_query($params) . '&appkey=' . $this->appkey;
		$debug['url_params'] = $url_params;
		//将URL参数字符串进行MD5密码
		$sign = md5($url_params);
		$debug['sign'] = $sign;

		// var_dump($debug);

		return $sign;
	}
	/**
	 * 是否AJAX请求
	 * @access protected
	 * @return bool
	 */
	protected function isAjax() {
		if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) ) {
			if('xmlhttprequest' == strtolower($_SERVER['HTTP_X_REQUESTED_WITH']))
				return true;
		}
		if(!empty($_POST[C('VAR_AJAX_SUBMIT')]) || !empty($_GET[C('VAR_AJAX_SUBMIT')]))
			// 判断Ajax方式提交
			return true;
		return false;
	}
	/**
	 * 返回错误信息
	 * @param  string $msg    [description]
	 * @param  [type] $data   [description]
	 * @param  [type] $status [description]
	 * @return [type]         [description]
	 */
	protected function json_error($msg='', $data, $status=400){
		$info['info']   = $msg;
		$info['data']   = $data;
		$info['status'] = $status;

		$json = json_encode($info);
		exit($json);
	}
}
?>